<?php

iQLvalidate($_GET['id']);
if(!$_GET['id'])
$_GET['id']=0;

SQLvalidate($_GET['cat']);
if(!$_GET['cat'])
$_GET['cat']=0;

if(!perms_check('article', 'read')) {
	redirect('index.php?module=error&amp;error=auth_error');
	exit;
}

//creating template
$tpl=new tpl;
$tpl->cache(true); //turn on cache
if($_GET['cat'])
$tpl->uri_modifier('_sort_'.$_SESSION['article_sortby'].'_'.$_SESSION['article_sort']);
$tpl_cached=$tpl->is_cached();

if($tpl_cached==false) {

	if(!$_GET['id'] && !$_GET['action']) {
		//link
		if(!$conf['mod_rewrite'])
			$link=cat_get_link($_GET['cat'], 'article', '<a href="{url}">{name}</a>');
		else
			$link=cat_get_link_mr($_GET['cat'], 'articles', '<a href="{url}">{name}</a>');
		//

		//adding form
		$sort_form = "<form action=\"index.php?function=set_default_sort_order&amp;what=article\" method=\"post\">$lang[sort_by]
			<select name=\"sortby\" class=\"button\">
			<option value=\"date\"";
		if($_SESSION['article_sortby'] == 'date')
			$sort_form .= ' selected';
		$sort_form .=">$lang[sort_date]</option>
			<option value=\"rating\"";
		if($_SESSION['article_sortby'] == 'rating')
			$sort_form .= ' selected';
		$sort_form .=">$lang[sort_rating]</option>
			<option value=\"title_$_SESSION[lang_short]\"";
		if($_SESSION['article_sortby'] == 'title_'.$_SESSION['lang_short'])
			$sort_form .= ' selected';
		$sort_form .=">$lang[sort_title]</option>
			</select>
			<select name=\"sort\" class=\"button\">
			<option value=\"ASC\" ";
		if($_SESSION['article_sort']=='ASC')
			$sort_form .= ' selected';
		$sort_form .=">$lang[search_asc]</option>
			<option value=\"DESC\" ";
		if($_SESSION['article_sort']=='DESC')
			$sort_form .= ' selected';
		$sort_form .=">$lang[search_desc]</option>
			</select>
			<input type=\"submit\" value=\"$lang[go]\" class=\"button\">
			</form>";
		//

		//adding list of subcategories
		SQLvalidate($_GET['rec_c']);
		if(!$_GET['rec_c'])
			$_GET['rec_c']=0;

		SQLvalidate($_GET['rec_a']);
		if(!$_GET['rec_a'])
			$_GET['rec_a']=0;

		$db->query("SELECT COUNT(id) as rec FROM $conf[prefix]categories WHERE article_".$_SESSION['lang_short'].">0 and parent = $_GET[cat]") or $db->err(__FILE__, __LINE__);
		$q=$db->fetch_object();
		$q=$q->rec;

		$category_sort_="ORDER BY $_SESSION[categories_sortby] ".$_SESSION['categories_sort'];
		$db->query("SELECT * FROM $conf[prefix]categories WHERE article_".$_SESSION['lang_short'].">0 and parent = $_GET[cat] $category_sort_ LIMIT $_GET[rec_c], $conf[categories_per_page]") or $db->err(__FILE__, __LINE__);

		$tmp=read_file('article_cat_item.php');
		$i=0;
		$categories='';
		while($c = $db->fetch_object()) {
			$t = 'desc_'.$_SESSION['lang_short'];
			$tl = 'name_'.$_SESSION['lang_short'];
			$count='article_'.$_SESSION['lang_short'];

			if($c->$t == '' && $c->$tl == '') {
				$tl = 'name_'.$conf['language'];
				$t = 'desc_'.$conf['language'];
				$count='article_'.$conf['language'];
			}

			$name_ = read_text_rest($c->$tl);
			$desc = read_text($c->$t);

			if($conf['mod_rewrite']) //jezeli wlaczony mod_rewrite
				$url='articles-'.read_text_mr($name_).'_'.$c->id.'.html';
			else
				$url='index.php?module=article&amp;cat='.$c->id;

			$categories .= string_template($tmp, array('theme_path'=>$GLOBALS['theme_path'], 'catname'=>$name_, 'catarticles'=>$c->$count, 'catdesc'=>$desc, 'catid'=>$c->id, 'i'=>(($i%2)+1), 'caturl'=>$url));
			$i++;
		}
		//

		//subcategries pages
		if($conf['mod_rewrite']) //jezeli wlaczony mod_rewrite
			$url=cat_get_mr($_GET['cat'], 'articles').'&amp;rec_a='.$_GET['rec_a'].'&amp;rec_c={rec}';
		else
			$url='index.php?module=article&amp;cat='.$_GET['cat'].'&amp;rec_a='.$_GET['rec_a'].'&amp;rec_c={rec}';

		$page_link_c=split_to_pages('<a href="'.$url.'">{nr}</a>', $conf['categories_per_page'], $q, $_GET['rec_c']);
		//

		//adding list of articles inside current cat
		$db->query("SELECT COUNT(id) as rec FROM $conf[prefix]article WHERE cat = $_GET[cat] and visible = 1") or $db->err(__FILE__, __LINE__);
		$q=$db->fetch_object();
		$q=$q->rec;

		$articles_sort_="ORDER BY ".$_SESSION['article_sortby']." ".$_SESSION['article_sort'];
		$db->query("SELECT * FROM $conf[prefix]article WHERE cat = $_GET[cat] and visible = 1 $articles_sort_ LIMIT $_GET[rec_a], $conf[categories_per_page]") or $db->err(__FILE__, __LINE__);

		$tmp=read_file('article_item.php');
		$i=0;
		$articles='';
		while($c = $db->fetch_object()) {
			$t = "text_$_SESSION[lang_short]";
			$tl = "title_$_SESSION[lang_short]";

			if($c->$t == '' && $c->$tl == '') {
				$tl = "title_$conf[language]";
				$t = "text_$conf[language]";
			}

			if($conf['mod_rewrite']) //jezeli wlaczony mod_rewrite
				$url='article-'.read_text_mr($c->$tl).'_'.$c->id.'_0.html';
			else
				$url='index.php?module=article&amp;id='.$c->id;

			$text = read_text(add_dots_($c->$t, 200)).string_template($lang['read_more'], array('theme_path'=>$GLOBALS['theme_path'], 'id'=>$c->id, 'url'=>$url));
			$title = read_text_rest($c->$tl);

			$articles .= string_template($tmp, array('theme_path'=>$GLOBALS['theme_path'], 'viewed'=> string_template($lang['articles_viewed'], array("n" => $c->viewed)), 'id'=>$c->id, 'i'=>(($i%2)+1), 'text'=>$text, 'name'=>$title, 'url' => $url));
			$i++;
		}
		//

		//articles pages
		if($conf['mod_rewrite']) //jezeli wlaczony mod_rewrite
			$url=cat_get_mr($_GET['cat'], 'article').'&amp;rec_a={rec}&amp;rec_c='.$_GET['rec_a'];
		else
			$url='index.php?module=article&amp;cat='.$_GET['cat'].'&amp;rec_a={rec}&amp;rec_c='.$_GET['rec_a'];

		$page_link_a=split_to_pages('<a href="'.$url.'">{nr}</a>', $conf['categories_per_page'], $q, $_GET['rec_a']);
		//

		$cur_cat_name='';
		$cur_cat_desc='';
		if($_GET['cat']){
			$q=get_cat_by_id($_GET['cat']);

			$t = "desc_$_SESSION[lang_short]";
			$tl = "name_$_SESSION[lang_short]";

			if($q->$t == '' && $q->$tl == '') {
				$t = "desc_$conf[language]";
				$tl = "name_$conf[language]";
			}

			$cur_cat_name=read_text_rest($q->$tl);
			$cur_cat_desc=read_text($q->$t);
		}

		//site_title
		$GLOBALS['lang']['global']['site_title']=read_text_rest($cur_cat_name).' - '.$GLOBALS['lang']['global']['site_title'];
		$GLOBALS['lang']['global']['site_description']=read_text_rest($cur_cat_name).' - '.$GLOBALS['lang']['global']['site_description'];
		$content = string_template(read_file('article_main.php'), array('theme_path' => $GLOBALS['theme_path'], 'link' => $link, 'sort_form' => $sort_form, 'page_link_c'=>$page_link_c, 'page_link_a'=>$page_link_a, 'categories' => $categories, 'articles' => $articles, 'cur_cat_name'=>$cur_cat_name, 'cur_cat_desc'=>$cur_cat_desc, 'content'=>$content));
	}
	elseif($_GET['id'] && !$_GET['action']) {
		//query start
		$db->query("SELECT * FROM $conf[prefix]article WHERE id=$_GET[id]") or $db->err(__FILE__, __LINE__);

		if($db->num_rows()==0) {
			redirect('index.php?module=error&amp;error=article_error1');
			exit;
		}

		$art = $db->fetch_object();

		if($art->visible != 1 && !perms_check('admin', 'panel')) {
			redirect('index.php?module=error&amp;error=article_error1');
			exit;
		}

		SQLvalidate($_GET['rec']);
		if(!$_GET['rec'])
			$_GET['rec'] = 0;

		//inkrementacja czytan
		$db->query("UPDATE $conf[prefix]article SET viewed = viewed+1 WHERE id = $_GET[id]") or $db->err(__FILE__, __LINE__);

		//przygotowywanie zmiennych do wyswietlenia
		$t = "text_$_SESSION[lang_short]";
		$tl = "title_$_SESSION[lang_short]";

		if($art->$t == '' or $art->$tl == '') {
			$tl = 'title_'.$conf['language'];
			$t = 'text_'.$conf['language'];
		}

		$title = read_text_rest($art->$tl);
		if(strpos($art->$t, '[end]')!==false)
			$text = explode('[end]', $art->$t);
		else {
			if(($pos = strpos($art->$t, "\r\n\r\n"))!==false) {
				$text[0] = substr($art->$t, 0, $pos);
				$text[1] = substr($art->$t, $pos+1); 
			} else $text = explode('[end]', $art->$t);
		}

		$pages = count($text)-1;

		if($_GET['rec']!=0) {
			$text_begin = '';
			$text = $text[$_GET['rec']+1];
		}
		else {
			$text_begin = $text[0];
			$text = $text[1];
		}

		//site_title
		$GLOBALS['lang']['global']['site_title']=read_text_rest($title).' - '.$GLOBALS['lang']['global']['site_title'];
		$GLOBALS['lang']['global']['site_description']=read_text_rest(strip_exbcode(add_dots_($text[0], 100))).' - '.$GLOBALS['lang']['global']['site_description'];

		$date = date($conf['date_format'], strtotime($art->date));
		$comments = $art->comments;

		//link, url
		if(!$conf['mod_rewrite']) {
			$page_url='index.php?module=article&amp;id='.$_GET['id'].'&amp;rec={rec}&amp;rec_c='.$_GET['rec_c'];
			$link=cat_get_link($art->cat, 'article', '<a href="{url}">{name}</a>');
		}
		else {
			$page_url='article-'.read_text_mr($art->$tl).'_'.$art->id.'_{rec}.html';
			$link=cat_get_link_mr($art->cat, 'articles', '<a href="{url}">{name}</a>');
		}
		//

		//page_link
		$page_link=split_to_pages('<a href="'.$page_url.'">{nr}</a>', 1, $pages, $_GET['rec']);
		//

		//adding {edit} & {delete} if user is admin
		if(perms_check('article', 'edit'))
			$edit='<a href="index.php?module=admin&amp;action=article&amp;cmd=edit&amp;id='.$art->id.'">'.$lang['admin_edit'].'</a>';
		else
			$edit='';

		if(perms_check('article', 'del'))
			$delete='<a href="index.php?module=admin&amp;action=article&amp;cmd=delete&amp;id='.$art->id.'">'.$lang['admin_delete'].'</a>';
		else
			$delete='';
		//

		$cmts='comments_'.$_SESSION['lang_short'];
		$content = string_template(read_file('article.php'), array('theme_path'=>$GLOBALS['theme_path'], 'viewed'=>string_template($lang['article_viewed'], array('n'=>$art->viewed)), 'link'=>$link, 'page_link' => $page_link, 'author' => get_user_overlib_by_id($art->author), 'title' => $title, 'date' => $date, 'edit' => $edit, 'delete' => $delete, 'votes' => $art->votes, 'rating' => $art->rating, 'id' => $art->id, 'comments' => string_template($lang['comments'], array('comments' => $art->$cmts, 'url'=>$url)), 'text' => read_text($text), 'text_begin'=>read_text($text_begin)));

		if(is_module_installed('comments')) {
			require_once("includes/functions/comments.php");
			$content .= comments('article', $art->id);
		}
	}
	elseif($_GET['action'] == 'suggest') {
		$tpl->cache(false);
		//select author
		$db = new dbquery;
		$db->query("SELECT * FROM $conf[prefix_users]users WHERE id='$_SESSION[id]' or id=1") or $db->err(__FILE__, __LINE__);

		while($u=$db->fetch_object()) {
			if($u->id!=$_SESSION['id'])
				$select_author.='<OPTION VALUE="'.$u->id.'">'.$u->name.' '.$u->surname.' ['. $u->login .']</OPTION>';
			else
				$select_author.='<OPTION VALUE="'.$u->id.'" SELECTED>'.$u->name.' '.$u->surname.' ['. $u->login .']</OPTION>';
		}
		//

		//add categories
		$ct = NULL;
		list_categories(0, 0, 'select', 1, $ct, 0);
		//

		$array = array('theme_path'=>$GLOBALS['theme_path'], 'function' => 'article_suggest', 'c_date' => date('Y-m-d H:i:s'), 'c_author' => $select_author, 'c_category' => $ct, 'checked' => ' checked', 'n_selected' => ' selected', 'c_image' => '', 'checked' => ' checked', 'c_size' => '', "ldate" => date($conf['date_format'], strtotime(date('Y-m-d H:i:s'))));

		$multi = NULL;

		$langs = get_lang_list();
		$i = 0;
		foreach($langs as $key => $l) {
			$i++;
			if($l==$_SESSION['lang_short']) {
				$icon = 'collapse';
				$style = 'block';
			}
			else {
				$icon = 'expand';
				$style = 'none';
			}

			$multi .= string_template(read_file('admin/themes/articles_form_multi.php'), array('lang' => $l, 'language' => strtoupper($l), 'icon' => $GLOBALS['theme_path'].$GLOBALS['theme_img'][$icon], 'style' => $style, 'i' => $i));
			$t = "title_$l";
			$array["c_$t"] = '';
			$t = "text_$l";
			$array["c_$t"] = '';

			//recover
			if(ereg('module=error', $_SERVER['HTTP_REFERER'])) {
				$t = "title_$l";
				$array["c_$t"] = $_SESSION['recover_'.$t];
				$t = "text_$l";
				$array["c_$t"] = $_SESSION['recover_'.$t];   
			}
			//		
		}

		$content = string_template(read_file('admin/themes/articles_form.php'), array('multi' => $multi));
		$content = string_template($content, $array);
	}
	//put $content to proper theme/file
	$content = string_template(read_file('middle.php'), array('theme_path' => $GLOBALS['theme_path'], 'content' => $content, 'description' => $lang['admin_articles']));

	//generating menus (what, template)
	$menu_left=menu('left', 'left');
	$menu_right=menu('right', 'right');
	$menu_top=menu('top', 'top');
	//

	//site_generation_time
	$GLOBALS['time_end'] = microtime(1);
	$site_generation_time=abs(round($GLOBALS['time_end']-$GLOBALS['time_start'], 3));
	//

	//header
	$tpl->create('header.php', array('title' => $GLOBALS['lang']['global']['site_title'], 'description' => $GLOBALS['lang']['global']['site_description'], 'keywords' => $GLOBALS['lang']['global']['site_keywords'], 'theme_path'=>$GLOBALS['theme_path'], 'menu_top' => $menu_top));
	//body
	$tpl->create('body.php', array('theme_path' => $GLOBALS['theme_path'], 'menu_top' => $menu_top, 'menu_left' => $menu_left, 'menu_right' => $menu_right, 'content' => $content));
	//footer
	$tpl->create('footer.php', array('site_generation_time' => string_template($GLOBALS['lang']['global']['site_generation_time'], array('site_generation_time'=>$site_generation_time, 'queries'=>$db->query_count())), 'theme_path'=>$GLOBALS['theme_path'], 'copyright' => $GLOBALS['lang']['global']['site_copyright'], 'queries'=>$db->query_count()));
	//parse
	$tpl->parse();
} else {
	//add uni / raw + update online database
	stats(true);

	//update files views
	if($_GET['id'] && !$_COOKIE['articleviewed_'.$_GET['id']]){
		$db = new dbquery;
		$db->query("UPDATE $conf[prefix]article SET viewed=viewed+1 WHERE id = ".$_GET['id']) or $db->err(__FILE__, __LINE__);
		setcookie('articleviewed_'.$_GET['id'], true);
	}

	if($_GET['id'] && $conf['mod_rewrite']) {
		$db->query("SELECT * FROM $conf[prefix]article WHERE id = ".$_GET['id']) or $db->err(__FILE__, __LINE__);
		$art=$db->fetch_object();
		$t='title_'.$_SESSION['lang_short'];
		$url=read_text_mr($art->$t).'_'.$art->id;

		//redirect 301 if wrong adress
		if(strpos(htmlspecialchars($_SERVER['REQUEST_URI']), $url)===false){
			redirect('article-'.$url.'_0.html', "HTTP/1.1 301 Moved Permanently");
			exit;
		}
		//
	}

	if($_GET['cat'] && $conf['mod_rewrite']) {
		$c=get_cat_by_id($_GET['cat']);

		$tl = "name_".$_SESSION['lang_short'];
		$url = read_text_mr($c->$tl).'_'.$c->id;

		//redirect 301 if wrong adress
		if(strpos(htmlspecialchars($_SERVER['REQUEST_URI']), $url)===false){
			redirect('articles-'.$url.'.html', "HTTP/1.1 301 Moved Permanently");
			exit;
		}
		//
	}

	//creating template
	$tpl->create();

	//parse
	$tpl->parse();
}
?>
